<?php
if(!defined('ROOT')){//view目录的上一级目录
	define('ROOT',dirname(dirname(dirname(dirname(__FILE__)))).'/' );
}

ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

require(ROOT_PATH.'config/config.php');
error_reporting(E_ERROR);
require_once(LIB_PATH."/myframe.php");//框架

require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
require_once ROOT_PATH.'model/order.model.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify{
	public function Queryorder($transaction_id){
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
				&& array_key_exists("result_code", $result)
				&& $result["return_code"] == "SUCCESS"
				&& $result["result_code"] == "SUCCESS")
		{//更新订单的状态
			$orderInfo = explode('--',$result['out_trade_no']);
			$fee = $result['cash_fee']/100;
			$shopId = intval($orderInfo[0]);
			$orderId = intval($orderInfo[1]);

			if($shopId==-1){//诚信金，没有卖家，商家交钱给系统
                $guaranteeOrder = new GuaranteeOrder();
                $guaranteeOrder->find($orderId);

                $uid = $guaranteeOrder->uid;
				$user = new User();
				$user->find($uid);

				$logOk = MoneyLogExt::write($guaranteeOrder->uid,SYSTEM_UID,$fee,MONEY_TYPE_GUARANTEE,$orderId,'用户缴纳诚信金');

				$user->guaranteeAmount = $user->guaranteeAmount + $fee;
				$user->save();

				//增加系统诚信金
				$sql = 'UPDATE tbl_user SET guaranteeAmount=guaranteeAmount+'.$fee.' WHERE uid='.SYSTEM_UID.' ';
				$user->query($sql);

                $guaranteeOrder->paidMoney = $fee;
                $guaranteeOrder->status = STATUS_PUBLISH;
                $guaranteeOrder->save();
			}else{//产品或者需求订单，有卖家，可以评价订单和维权
				$order = new Order();
				$order->find(['orderId'=>$orderId]);
				if($order->demandId){//需求招标，需求方付费
					$logOk = MoneyLogExt::write($order->buyerUid,SYSTEM_UID,$fee,MONEY_TYPE_DEMAND,$orderId,'需求托管金');

					//update demand status
					$demand = new Demand();
					$demand->find($order->demandId);
					$demand->status = STATUS_DEMAND_PAID;
					$demand->save();

					//update demand reply status
					$selectedReplyId = $demand->replyId;
					$demandReply = new DemandReply();
					$sql= "SELECT * FROM tbl_demand_reply WHERE demandId={$order->demandId};";
					$result = $demandReply->query($sql);
					foreach($result as $tmpReply){
						if($tmpReply['demandReplyId'] == $selectedReplyId){
							$status = STATUS_REPLY_WIN;

							//message to seller,win bid
							$message = new Message();
							$message->uid = $tmpReply['fromUid'];
							$title = $demand->title;
							if(mb_strlen($title)>20) $title=mb_substr($title,0,20).'...';
							$message->title = "中标提醒：您已中标“{$title}”，客户已支付{$fee}元，请尽快与客户沟通进行服务";
							$message->url = "/my/bid/list";
							$message->save();
						}else{
							$status = STATUS_REPLY_LOST;
						}
						$sql = 'UPDATE tbl_demand_reply SET myBidStatus='.$status.' WHERE demandReplyId='.$tmpReply['demandReplyId'];
						$demandReply->query($sql);
					}

				}else{//商品订单
					$logOk = MoneyLogExt::write($order->buyerUid,SYSTEM_UID,$fee,MONEY_TYPE_PRODUCT,$orderId,'购买产品');

					//message to seller,buy product
					$message = new Message();
					$message->uid = $order->sellerUid;
					$title = $order->title;
					if(mb_strlen($title)>20) $title=mb_substr($title,0,20).'...';
					$message->title = "订单提醒“{$title}”，客户已支付{$fee}元，请尽快与客户沟通进行服务";
					$message->url = "/my/order/list";
					$message->save();
				}

				if($logOk){
					$order->buyerPay = $fee;
					$order->status = STATUS_BUYER_PAID;
					$order->payTime = date('Y-m-d H:i:s');
					$order->save();
				}
			}
			Log::DEBUG("====call back orderId=:" .$result['out_trade_no'].' $orderId='.$orderId.' $shopId='.$shopId );

			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg)	{


		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();

		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return true;
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
